from .chessBoard import ChessBoard
from .user import Rooms

class Room:
    def __init__(self, manage):
        self.__id = ""
        self.__name = ""
        self.member = [manage]
        self.__manage = manage
        self.__maxMember = 2
        self.__record = []

    def toJson(self):
        return {
            "name": self.__name,
            "members": [item.name for item in self.member],
            "maxMember": self.__maxMember,
            "manage": self.__manage.name
        }

    # 是否满员
    def isFull(self):
        return self.__maxMember <= len(self.member)

    # 获取成员数
    def length(self):
        return len(self.member)

    # 获取管理员 房主
    def getManage(self):
        return self.__manage

    # 获取房间名
    def getName(self):
        return self.__name

    # 更改房间名
    def setName(self, name):
        self.__name = name

    # 加入
    def join(self, user):
        user.room = self
        if not self.isFull():
            self.member.append(user)
            for item in self.member:
                item.ws.send('joinRoomMesssage', {'mes': f'{user.name}已加入'})
        else:
            user.ws.send('joinRoom', {'code': -1, 'mes': '房间已满'})

        if self.isFull():
            self.start()

    # 通知每个人开始游戏
    def start(self):
        chess = ChessBoard(self)
        for user in self.member:
            user.setChess(chess)
            user.ws.send('roomStart', {'mes': '准备开始'})

    # 退出
    def exit(self, **kwarg):
        for user in self.member:
            user.ws.send('room.exit', {'mes': '有成员退出，房间已销毁'})
            user.room = None
            user.chessBoard = None
        Rooms.remove(self)

    # 聊天
    def chat(self, **kwargs):
        title = kwargs.get('title')
        message = kwargs.get('message')
        for user in self.member:
            user.ws.send('room.chat', {'title': title, 'message': message})
